package com.ushio.capsuleservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ushio.capsuleservice.model.dto.ApiResponse;
import com.ushio.capsuleservice.model.entity.Container;
import com.ushio.capsuleservice.service.ContainerService;
// TODO: 后续加上用户登录后，解注释以下代码
// import com.ushio.capsuleservice.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 时间容器控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/container")
@CrossOrigin(origins = "*")
public class ContainerController {
    
    @Autowired
    private ContainerService containerService;
    
    // TODO: 后续加上用户登录后，解注释以下代码
    // @Autowired
    // private JwtUtil jwtUtil;
    
    /**
     * 创建时间容器
     */
    @PostMapping
    public ApiResponse<Container> createContainer(@RequestBody Container container, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 暂时使用默认用户ID = 1
            Long userId = 1L;
            container.setUserId(userId);
            
            Container createdContainer = containerService.createContainer(container);
            return ApiResponse.success("创建成功", createdContainer);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户的时间容器列表（支持完整搜索功能）
     */
    @GetMapping
    public ApiResponse<IPage<Container>> getUserContainers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String start_date,
            @RequestParam(required = false) String end_date,
            @RequestParam(required = false) BigDecimal min_score,
            @RequestParam(required = false) BigDecimal max_score,
            HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 暂时使用默认用户ID = 1
            Long userId = 1L;
            
            IPage<Container> containers = containerService.getUserContainers(
                userId, page, size, status, keyword, category, start_date, end_date, min_score, max_score);
            return ApiResponse.success(containers);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取时间容器详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Container> getContainerDetail(@PathVariable Long id) {
        try {
            Container container = containerService.getContainerDetail(id);
            if (container == null) {
                return ApiResponse.error("时间容器不存在");
            }
            return ApiResponse.success(container);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    /**
     * 更新时间容器
     */
    @PutMapping("/{id}")
    public ApiResponse<Container> updateContainer(@PathVariable Long id, HttpServletRequest request) {
        try {
//            String token = getTokenFromRequest(request);
//            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 检查是否是容器作者
//            Container existingContainer = containerService.getById(id);
//            if (existingContainer == null || !existingContainer.getUserId().equals(userId)) {
//                return ApiResponse.error("无权限修改此容器");
//            }
            log.info("我要更新id-: {}", id);
            Container updatedContainer = containerService.updateContainer(id, new Container());
            return ApiResponse.success("更新成功", updatedContainer);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 结束时间容器
     * @param id 容器id
     *
     */
    @PostMapping("/{id}/end")
    public ApiResponse<Container> endContainer(@PathVariable Long id, HttpServletRequest httpRequest) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(httpRequest);
            // Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 暂时使用默认用户ID = 1
            Long userId = 1L;
            
            // 检查是否是容器作者 todo 后续加上用户登录后
//            Container existingContainer = containerService.getById(id);
//            if (existingContainer == null) {
//                return ApiResponse.error("容器不存在");
//            }
            // TODO: 后续加上用户登录后，解注释以下代码
            // if (!existingContainer.getUserId().equals(userId)) {
            //     return ApiResponse.error("无权限操作此容器");
            // }
            
            Container endedContainer = containerService.endContainer(id);
            return ApiResponse.success("容器已结束", endedContainer);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 删除时间容器
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteContainer(@PathVariable Long id, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 暂时使用默认用户ID = 1
            Long userId = 1L;
            
            // 检查是否是容器作者
            Container existingContainer = containerService.getById(id);
            if (existingContainer == null) {
                return ApiResponse.error("容器不存在");
            }
            // TODO: 后续加上用户登录后，解注释以下代码
            // if (!existingContainer.getUserId().equals(userId)) {
            //     return ApiResponse.error("无权限删除此容器");
            // }
            
            boolean success = containerService.deleteContainer(id);
            if (success) {
                return ApiResponse.success("删除成功", null);
            } else {
                return ApiResponse.error("删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户进行中的容器数量
     */
    @GetMapping("/active/count")
    public ApiResponse<Map<String, Long>> getActiveContainerCount(HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 暂时使用默认用户ID = 1
            Long userId = 1L;
            
            long count = containerService.getActiveContainerCount(userId);
            Map<String, Long> data = new HashMap<>();
            data.put("count", count);
            
            return ApiResponse.success(data);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    
    // TODO: 后续加上用户登录后，解注释以下代码
    // /**
    //  * 从请求中获取token
    //  */
    // private String getTokenFromRequest(HttpServletRequest request) {
    //     String bearerToken = request.getHeader("Authorization");
    //     if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
    //         return bearerToken.substring(7);
    //     }
    //     throw new RuntimeException("未找到有效的token");
    // }
}
